/**
 * 准备函数
 */
var ckList = new Array();
$(document).ready(function() {
	
	// 加载表格
	queryPlayVersion();
	
	// 绑定函数
	$("#queryButton").bind("click", confirmQueryPlayVersion);
	$("#createButton").bind("click", showCreatePlayVersionDialog);
	$("#confirmCreateButton").bind("click", confirmCreatePlayVersion);
	$("#confirmSetPVCButton").bind("click", confirmSetPVC);
	
	// 加载form模块
	layui.use(['form', 'laydate'], function() {
		$form = layui.form;
		$form.on('checkbox(cIsGeneral)', function(data) {
			if (data.elem.checked) {
				$(".companyTr").hide();
			}else{
				$(".companyTr").show();
			}
		});
	});
	
	// 列表 全选、反选
	var selectListAll = "selectListAll";
	var rowCheckbox = "companyItem";
	$("#" + selectListAll).click(function() {
		selectCbAll(this, rowCheckbox, ckList);
	});
	
	// 列表单个 全选、反选
	$(document).on("click", "input[name='" + rowCheckbox + "']", function() {
		selectCbOne(this, selectListAll, rowCheckbox, ckList);
	});
});

/**
 * 确认查询
 */
function confirmQueryPlayVersion(){
	queryPlayVersion();
}

/**
 * 查询
 */
function queryPlayVersion(pageIndex,pageSize) {
	// 组装参数
	var data = {};
	
	//设置分页参数
	setPageIndex(data,pageIndex,pageSize);
	
	// 调用接口
	var response = callInterface("post", "playVersion/queryPlayVersion",
			data, false);
	if (response.code == 0) {
		var count = response.data.totalCount;
		if (count == null) {
			count = 0;
		}
		
		// 清空表格及分页
		$("#playVersionTable tr:not(:first)").remove();
		$("#pageDiv").html("");

		// 动态添加一行
		if (count == 0) {
			var cols = $("#playVersionTable").find("tr:first th");
			$('#playVersionTable').append(
					"<tr><td colspan='" + cols.length + "'>无数据!</td></tr>");
			return false;
		}
		
		var list = response.data.list;
		if (list != null && list.length > 0) {
			for ( var i in list) {
				var trHtml = "<tr>";
				trHtml += "<td align='center'>" + Utils.convertNull(list[i].version) + "</td>";
				trHtml += "<td align='center'>" + Utils.convertNull(list[i].fileMd5) + "</td>";
				trHtml += "<td align='center'>" + (list[i].isGeneral?'是':"否") + "</td>";
				var str = Utils.isNotNull(list[i].companyName)?list[i].companyName+"：":"";
				if(Utils.isNotNull(str)){
					if(Utils.isNotNull(list[i].description)){
						str += list[i].description;
					}else{
						str = str.substring(0, str.length-1);
					}
				}else{
					str = Utils.convertNull(list[i].description);
				}
				trHtml += "<td align='center'>" + str + "</td>";
				trHtml += "<td align='center'>" + Utils.convertNull(list[i].createdTime) + "</td>";
				trHtml += "<td align='center'><a href='"+list[i].packageUrl+"' download='download'>下载</a></td>";
				trHtml += "</tr>";

				// 动态添加一行
				$('#playVersionTable').append(trHtml);
			}
		}

		// 调用分页
		layui.use(['laypage'], function() {
			var laypage = layui.laypage;
			laypage.render({
				elem : 'pageDiv',
				// pages : pages,
				curr : pageIndex || 1, // 当前页
				count : count,
				limit : pageSize,
				skip : true, // 是否开启跳页
				layout : ['count', 'prev', 'page', 'next', 'limit', 'skip'],
				groups : 5, // 连续显示分页数
				jump : function(obj, first) { // 触发分页后的回调
					// 一定要加此判断，否则初始时会无限刷新
					if (!first) {
						// 点击跳页触发函数自身，并传递当前页：obj.curr
						queryPlayVersion(obj.curr,obj.limit);
					}
				}
			});
		});
	}
}

/**
 * 显示创建对话框
 */
function showCreatePlayVersionDialog() {
	// 显示对话框
	$("#createPlayVersionDialog").modal({
		backdrop : 'static',
		keyboard : false,
		show : true
	});
	$('#cPackageUrl').val('');
	$('#addPlayForm')[0].reset();
	$("#cIsGeneral").prop('checked',true);
	$(".companyTr").hide();
}
 
/**
 * 确认创建
 */
function confirmCreatePlayVersion() {
	// 获取参数
	var data = {};
	var version = $.trim($("#cVersion").val());
	if (version == "") {
		showAlert('版本号不能为空!');
		return false;
	}
	data['version'] = version;
	var packageUrl = $.trim($("#cPackageUrl").val());
	if (packageUrl == "") {
		showAlert('请上传版本文件!');
		return false;
	}
	data['packageUrl'] = packageUrl;
	var isGeneral = $('#cIsGeneral').is(":checked");
	data['isGeneral'] = isGeneral;
	
	if(!isGeneral){
		var companyId = $.trim($("#cCompanyId").val()); 
		if (Utils.isNull(companyId)) {
			showAlert('非通用版本必须选择一个公司，请检查!');
			return false;
		}
		data['companyId'] = companyId;
	}
	data['fileMd5'] = fileMd5;
	data['description'] = $.trim($("#cDescription").val());
	
	// 调用接口
	var response = callInterface("post", "playVersion/createPlayVersion",
			data, false);
	if (response.code == 0) {
		showMsg('操作成功!');

		// 关闭对话框
		$('#createPlayVersionDialog').modal("hide");

		// 刷新
		queryPlayVersion();
	} else {
		showErrorMsg(response.code, response.message);
	}

	// 必须返回false,否则表单会自己再做一次提交操作,并且页面跳转
	return false;
}

/**
 * 显示创建对话框
 */
function toSetPlayVersionCompany(version) {
	// 显示对话框
	$("#setPlayVersionCompanyDialog").modal({
		backdrop : 'static',
		keyboard : false,
		show : true
	});
	$('#version').val(version);
	$("#selectListAll").prop("checked", false);
	$("input[name='companyItem']").prop("checked", false);
	
	// 获取版本公司
	getPlayVersionCompany(version);
}

function getPlayVersionCompany(version){
	// 调用接口
	var response = callInterface("post", "playVersion/queryCompany", {
		"version" : version
	}, false);

	if (response.code == 0) {
		var data = response.data;
		if (data != null) {
			for(var i in data){
				$("#companyItem_"+data[i]).prop("checked", true);
			}
		}
		// 4.处理分页后的复选框选中逻辑
		handlePageCb('selectListAll', 'companyItem');
	} else {
		showErrorMsg(response.code, response.message);
	}
}

/**
 * 确认设置
 */
function confirmSetPVC(){
	// 获取参数
	var data = {};
	var version = $.trim($("#version").val());
	if (version == "") {
		showAlert('版本号不能为空!');
		return false;
	}
	data['version'] = version;
	
	if (ckList.length > 0) {
		data['companyIdList'] = ckList;//JSON.stringify(ckList);
	}else {
		showAlert("请选择公司!");
		return;
	}
	
	// 调用接口
	var response = callInterface2("post", "playVersion/grantCompany", JSON.stringify(data), false);
	if (response.code == 0) {
		showMsg('操作成功!');

		// 关闭对话框
		$('#setPlayVersionCompanyDialog').modal("hide");
	} else {
		showErrorMsg(response.code, response.message);
	}
}

/**
 * 上传图片并预览 
 * $imageUrlFile:图片文件 
 * $imageShowDiv:图片预览 
 * $imageUrlId:图片UrlID
 * $fileType:文件类型(0:其他文件; 1:用户头像; 2:设备; 3:广告素材; 4：数据报告; 5:公司资料; 6:效果监播)
 */
var fileMd5;
function showUploadPlayVersionFile($imageUrlFile, $imageShowDiv, $imageUrlId, $fileType) {
	var fileObjs = document.getElementById($imageUrlFile);
	var file = fileObjs.files[0];
	var fileName = file.name;
	var suffix = (fileName.substring(fileName.lastIndexOf(".")+1,fileName.length)).toLowerCase(); 
	if(suffix != "apk"){
		Utils.showCustomTips($imageUrlFile, 1, "请上传APK文件!", '#000', '#ffe74c', 5);
		return false;
	}
	var formdata = new FormData();
	formdata.append("dataFile", file);
	formdata.append("fileType", $fileType);
	$.ajax({
		type : 'POST',
		url : 'file/uploadFile',
		data : formdata,
		dataType : "json",
//			async : false,
		cache : false,
		contentType : false,// 必须false才会自动加上正确的Content-Type
		processData : false,// 必须false才会避开jQuery对formdata的默认处理,XMLHttpRequest会对 formdata进行正确的处理
		beforeSend : function() {
			//创建LoadingDiv
			createLoadingDiv();
		},
		success : function(response) {
			if (response.code == 0) {
				// 获取返回路径
				$("#" + $imageUrlId).val(response.data.url);
				fileMd5 = response.data.fileMd5;
			} else {
				showAlert(response.message);
			}
		},
		error : function(data) {
			//关闭LoadingDiv
			closeLoadingDiv();
			showAlert(file+"上传失败!");
		}, 
		complete : function() {
			//关闭LoadingDiv
			closeLoadingDiv();
		}
	});
	return false;
}